package com.bcdbook.activiti.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 启动前的用户配置类
 *
 * @author summer
 * @date 2018-12-29 17:24
 * @version V1.0.0-RELEASE
 */
@Configuration
@Slf4j
public class MemoryUserConfiguration {

    /**
     * 注入 security 的工具类
     */
    @Resource
    private SecurityUtil securityUtil;

    /**
     * 设置用户
     *
     * @author summer
     * @date 2018-12-29 17:24
     * @return org.springframework.security.core.userdetails.UserDetailsService
     * @version V1.0.0-RELEASE
     */
    @Bean
    public UserDetailsService myUserDetailsService() {

        // 创建用户内存的信息
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        // 定义用户/用户组及角色集合
        String[][] usersGroupsAndRoles = {
                {"admin", "password", "ROLE_ACTIVITI_ADMIN"},
                {"someone", "password", "ROLE_ACTIVITI_USER"},
                {"manager", "password", "ROLE_ACTIVITI_USER", "GROUP_manager"},
                {"director", "password", "ROLE_ACTIVITI_USER", "GROUP_director"},
                {"hr", "password", "ROLE_ACTIVITI_USER", "GROUP_hr"},
                {"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"},
        };

        // 循环用户角色信息
        for (String[] user : usersGroupsAndRoles) {
            // 复制出用户的角色和用户组, 并生成新的集合, 并作为用户的权限
            List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
            log.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");

            /*
             * 创建用户
             */
            inMemoryUserDetailsManager
                    .createUser(
                            // 封装用户对象 (用户名, 加密后的密码, 权限)
                            new User(user[0],
                                    securityUtil.passwordEncoder().encode(user[1]),
                                    authoritiesStrings.stream().map(SimpleGrantedAuthority::new)
                                            .collect(Collectors.toList())
                            )
                    );
        }

        return inMemoryUserDetailsManager;
    }

}
